﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BookClubIt
{
    public partial class discussions : BasePage
    {
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
            hdnBid.Value = CID.ToString();

            DTO.BookClub club = BookClubProcessorInstance.GetBookClubById(CID);

            var club_Name = club.Name;
            lblClubName.Text = club.Name;

            //get current book
            DTO.Book currentBook = BookProcessorInstance.GetCurrentBook(CID);
            if (currentBook.Id == 0)
            {
                btnOpenModal.Visible = false;
                pnlNoCurrentBook.Visible = true;
            }
            else
            {
                lnkCurrentTitle.Text = currentBook.Title;
                lnkCurrentTitle.NavigateUrl = "../book.aspx?id=" + currentBook.Id;
            }
            // get current topics
            DTO.Topics topic = BookClubProcessorInstance.GetDiscussionTopics(CID, true);
            grdDiscussionTopics.DataSource = topic;
            grdDiscussionTopics.DataBind();

            // get all topics
            DTO.Topics alltopics = BookClubProcessorInstance.GetDiscussionTopics(CID, false);
            if (alltopics.Count > 0)
            {
                rptAllDiscussions.DataSource = alltopics;
                rptAllDiscussions.DataBind();
            }
            else
            {
                pnlOtherDiscussions.Visible = false;
            }
            if (BookClubProcessorInstance.IsLeader(CurrentUserId, CID) || BookClubProcessorInstance.IsAdmin(CurrentUserId, CID) || (club.NonLeaderAddTopics == 1 && BookClubProcessorInstance.IsBookClubMember(CurrentUserId, CID)) && currentBook.Id != 0)
            {
                btnOpenModal.Visible = true;
            }
        }

        private void BindData()
        {
           

        }
        public void BindData(DTO.Topics topics)
        {
            grdDiscussionTopics.DataSource = topics;
            grdDiscussionTopics.DataBind();
        }
        protected void rptAllDiscussions_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {

            hdnBid.Value = CID.ToString();

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DTO.Topic topic = e.Item.DataItem as DTO.Topic;
                HyperLink lnkprevioustopic = ((HyperLink)e.Item.FindControl("lnkprevioustopic"));
                Label lblPrevBookTitle = ((Label)e.Item.FindControl("lblPrevBookTitle"));

                  // DTO.Book prevbook = BookProcessorInstance.GetBookById(topic.Book_Id);
                  // lblPrevBookTitle.Text = prevbook.Title;

                DTO.Comments getComments = BookClubProcessorInstance.GetTopicComments(topic.Id);

                int topicCount = getComments.Count;
                lnkprevioustopic.NavigateUrl = "topic.aspx?id=" + CID + "&tid=" + topic.Id;
                lnkprevioustopic.Text = topic.Topic_Name + " (" + topicCount + " comments)";
            }
        }
        protected void grdDiscussionTopics_OnRowDataBound(object sender, GridViewRowEventArgs e)
        {
            DTO.Topic topic = e.Row.DataItem as DTO.Topic;

             if (e.Row.RowType != DataControlRowType.DataRow)
                return;

             if (e.Row.RowType == DataControlRowType.DataRow)
             {
                 HyperLink lnkTopic = ((HyperLink)e.Row.FindControl("lnkTopic"));
                 HyperLink lnkLatestCommentMember = ((HyperLink)e.Row.FindControl("lnkLatestCommentMember"));
                 Label lblPostCount = ((Label)e.Row.FindControl("lblPostCount"));
                 Label lblPostAbout = ((Label)e.Row.FindControl("lblPostAbout"));
                 Label lblRecentActivity = ((Label)e.Row.FindControl("lblRecentActivity"));

                 int tid = topic.Id;

                 DTO.Comments getComments = BookClubProcessorInstance.GetTopicComments(tid);

                 lnkTopic.NavigateUrl = "topic.aspx?id=" + hdnBid.Value + "&tid=" + tid;
                 lnkTopic.Text = topic.Topic_Name;
                 DTO.Book postaboutbook = BookProcessorInstance.GetBookByASIN(topic.ASIN);
                 lblPostAbout.Text = postaboutbook.Title;
                 
                 lblPostCount.Text = getComments.Count.ToString();

                 DTO.Comment getLatestComment = BookClubProcessorInstance.GetLatestComment(tid);
                 DTO.Member membercomment = MemberProcessorInstance.GetMemberById(getLatestComment.User_Id);

                 if (getComments.Count == 0)
                 {
                     lblRecentActivity.Text = "No comments";
                     lnkLatestCommentMember.Visible = false;
                 }
                 else
                 {
                     lblRecentActivity.Text = TimeAgo(getLatestComment.Comment_Date).ToString() + " by ";
                     lnkLatestCommentMember.NavigateUrl = "../member.aspx?uid=" + membercomment.Id;
                    lnkLatestCommentMember.Text = membercomment.Username.ToString();
                 }
             }
        }

         protected void btnCreateTopic_Click(object sender, EventArgs e)
          {
             
                 DTO.Book current = BookProcessorInstance.GetCurrentBook(CID);

                 string username = HttpContext.Current.User.Identity.Name.ToString();
                 DTO.Member member = MemberProcessorInstance.GetMemberByUsername(username);
                 int CurrentUserId = member.Id;

                 var CurrentASIN = current.ASIN.ToString();
                 var bookid = current.Id;
                 if (HttpContext.Current.User.Identity.IsAuthenticated && BookClubProcessorInstance.IsBookClubMember(CurrentUserId, CID))
                 {

                     DTO.BookClub topic = BookClubProcessorInstance.CreateTopic(CID, bookid, txtTopicName.Text, CurrentASIN);
                     BookClubProcessorInstance.AddClubActivity(CID, CurrentUserId, "ADDTOPIC", topic.Id);
                     BindData();
                 }
             }

         static string TimeAgo(DateTime time)
         {
             DateTime startDate = DateTime.Now;
             TimeSpan deltaMinutes = startDate.Subtract(time);
             string distance = string.Empty;
             if (deltaMinutes.TotalMinutes <= (8724 * 60))
             {
                 distance = DistanceOfTimeInWords(deltaMinutes.TotalMinutes);
                 if (deltaMinutes.Minutes < 0)
                 {
                     return distance + " from  now";
                 }
                 else
                 {
                     return distance + " ago";
                 }
             }
             else
             {
                 return "on " + time.ToString();
             }
         }
         static string DistanceOfTimeInWords(double minutes)
         {
             if (minutes < 1)
             {
                 return "less than a minute";
             }
             else if (minutes < 50)
             {
                 return Math.Round(minutes).ToString() + " minutes";
             }
             else if (minutes < 90)
             {
                 return "about one hour";
             }
             else if (minutes < 1080)
             {
                 return Math.Round(new decimal((minutes / 60))).ToString() + " hours";
             }
             else if (minutes < 1440)
             {
                 return "one day";
             }
             else if (minutes < 2880)
             {
                 return "about one day";
             }
             else
             {
                 return Math.Round(new decimal((minutes / 1440))).ToString() + " days";
             }
         }
    }
}